package com.diamond.facade;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

import com.diamond.bo.ClientOrderBO;
import com.diamond.bo.ClientOrderDetailBO;
import com.diamond.bo.InlayDiamonBO;
import com.diamond.bo.OrderBO;
import com.diamond.bo.QueryOrderBO;
import com.diamond.bo.ReturnBO;
import com.diamond.entity.Clientorder;
import com.diamond.entity.Clientorderdetail;
import com.diamond.entity.Diamond;
import com.diamond.entity.TInlayDiamond;
import com.diamond.service.IClientorderService;
import com.diamond.service.IClientorderdetailService;
import com.diamond.service.IDiamondService;
import com.diamond.service.IInlayDiamondService;
import com.diamond.util.DateUtils;
import com.diamond.util.StringUtil;

public class ClientorderFacade extends CommonFacade<ClientOrderBO> {

	public IClientorderService clientorderService;
	public IDiamondService diamondService;
	public IInlayDiamondService rangService;
	public IClientorderdetailService detailService;
	
	public void setDetailService(IClientorderdetailService detailService) {
		this.detailService = detailService;
	}

	public void setRangService(IInlayDiamondService rangService) {
		this.rangService = rangService;
	}

	public void setDiamondService(IDiamondService diamondService) {
		this.diamondService = diamondService;
	}

	public void setClientorderService(IClientorderService clientorderService) {
		this.clientorderService = clientorderService;
	}

	public ReturnBO<ClientOrderBO> queryClientOrder(QueryOrderBO queryOrderBo) throws Exception {
		return clientorderService.queryClientOrder(queryOrderBo);
	}

	public OrderBO queryClientOrderById(String cliOrdMasterId)throws Exception {
		OrderBO orderBo = clientorderService.queryClientOrderById(cliOrdMasterId);
		return orderBo;
	}

	public Map findOrder(Long id) {
		try {
			Clientorder bo=(Clientorder) clientorderService.findById(id);
			if(bo!=null){
				Map map = new HashMap();
				map.put("order", bo);
				String HQL="from Clientorderdetail where cliOrdMasterId="+id;
				List list=clientorderService.findByHQL(HQL);
				if(list!=null&&list.size()>0){
					List list1=new ArrayList<Clientorderdetail>();
					List list2=new ArrayList<Clientorderdetail>();
					for(int i=0;i<list.size();i++){
						Clientorderdetail detail = (Clientorderdetail) list.get(i);
						ClientOrderDetailBO dest=new ClientOrderDetailBO();
						PropertyUtils.copyProperties(dest, detail);
						if("0".equals(dest.getState()))dest.setState("未处理");
						if("1".equals(dest.getState()))dest.setState("订购成功");
						if("2".equals(dest.getState()))dest.setState("缺货");
						if(dest.getType()!=null&&"钻石".equals(dest.getType())){
							list1.add(dest);
						}else{
							list2.add(dest);
						}
					}
					map.put("details", list1);
					map.put("rangDetails", list2);
				}
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	public void saveOrderAndDetail(ClientOrderBO bo, List details,Object id,Object angent_id) {
		try {
			bo.setCliOrdMasterId(null);
			bo.setUserId((Long) id);
			bo.setOrderStatus("0");
			bo.setDelState("0");
			bo.setOrderNo("NO"+new Date().getTime());
			Clientorder order = new Clientorder();
			PropertyUtils.copyProperties(order, bo);
			clientorderService.save(order,details,angent_id);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	public void addDia(Map session, HttpServletRequest request) {
		try {
			List list=null;
	   		Object obj=session.get(session.get("USER_ID")+"_selected");
	    	if(obj!=null){
	    		list=(List)obj;
	    	}else{
		   		list=new ArrayList();
	    	}
	    	Diamond dia=diamondService.findByBatch(request.getParameter("batch"));
	    	Boolean has=false;
	    	for(int i=0;i<list.size();i++){
	    		ClientOrderDetailBO bo =(ClientOrderDetailBO)list.get(i);
   				if(bo.getBatch().equals(request.getParameter("batch"))){
   					has=true;
   					break;
   				}
   				
   			}
	    	if(!has){
	    		ClientOrderDetailBO detail = new ClientOrderDetailBO();
	    		detail.setAmount(1);
	    		detail.setBatch(dia.getBatch());
	    		detail.setClarity(dia.getClarity());
	    		detail.setColor(dia.getColor());
	    		detail.setFinalCut(dia.getFinalCut());
	    		detail.setFluor(dia.getFluor());
	    		detail.setHR(dia.getHR());
	    		detail.setLab(dia.getLab());
	    		detail.setName("钻石");
	    		detail.setPolish(dia.getPolish());
	    		detail.setPrice(Double.parseDouble(request.getParameter("price")));
	    		detail.setReportNo(dia.getReportNo());
	    		detail.setShape(dia.getShape());
	    		detail.setState("0");
	    		detail.setSupplierName(dia.getSupplierName());
	    		detail.setSymmetry(dia.getSymmetry());
	    		detail.setType("钻石");
	    		detail.setWeight(dia.getWeight());
	    		list.add(detail);
	    		session.put(session.get("USER_ID")+"_selected",list);
	   		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	public void delDia(Map session, HttpServletRequest request) {
		Object obj=session.get(session.get("USER_ID")+"_selected");
		if(obj!=null){
   			List list=(List)obj;
   			for(int i=0;i<list.size();i++){
   				ClientOrderDetailBO bo =(ClientOrderDetailBO)list.get(i);
   				if(bo.getBatch().equals(request.getParameter("batch"))){
   					list.remove(bo);
   				}
   				
   			}
   			session.put(session.get("USER_ID")+"_selected",list);
		}
		
	}

	public Map updateOrder(ClientOrderBO clientOrderBo) {
		try {
			if(clientOrderBo==null)return null;
			Clientorder bo = new Clientorder();
			PropertyUtils.copyProperties(bo, clientOrderBo);
			clientorderService.update(bo);
			return findOrder(bo.getCliOrdMasterId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void addInlay(Map session, HttpServletRequest request,ClientOrderDetailBO cdetail) {
		try {
			Long inlayId=cdetail.getInlayDiamondId();
			Double price=cdetail.getPrice();
			
			if(inlayId==null||price==null)return;
			String orderNO=(String) session.get("orderNo");
			if(StringUtils.isEmpty(orderNO))return;
			//查询钻托的成本价
			Double midPrice = 0d;
	    	TInlayDiamond inlayDiamond=(TInlayDiamond) rangService.findById(inlayId);
			if(!StringUtil.isEmpty(inlayDiamond.getInlayNumber())) {
				if ("PT900".equals(cdetail.getMaterial())) {
					midPrice = inlayDiamond.getPt900Price();
				} else if ("PT950".equals(cdetail.getMaterial())) {
					midPrice = inlayDiamond.getPt950Price();
				} else if ("18K".equals(cdetail.getMaterial())) {
					midPrice = inlayDiamond.getK18Price();
				}
			} else {
				return ;
			}
	    	String updateOrderTotalPriceSql = "update clientorder set total = total+"+ price +",mid_total = mid_total + "+ midPrice +"  where order_no = '"+orderNO+"'";
	    	
	    	if(inlayDiamond!=null){
	    		String cmpName="";
	    		List cmps=rangService.findBySQL("select cmp_name from user where user_id="+inlayDiamond.getUserId());
	    		if(cmps!=null&&cmps.size()>0){
	    			cmpName=cmps.get(0).toString();
	    		}
	    		Clientorderdetail detail = new Clientorderdetail();
	    		detail.setAmount(1);
	    		detail.setOrderCmpName(session.get("CMP_NAME").toString());
	    		detail.setCmpName(cmpName);
	    		detail.setMaterial(cdetail.getMaterial());
	    		detail.setOrderNo(orderNO);
	    		detail.setHand(cdetail.getHand());
	    		detail.setText(cdetail.getText());
	    		detail.setInlayDiaBatch((String) session.get("batch"));
	    		detail.setInlayBatch(inlayDiamond.getInlayNumber());
	    		detail.setInlayFactoryBatch(inlayDiamond.getFactoryNumber());
	    		detail.setName(inlayDiamond.getInlayName());
	            detail.setPrice(price);

	            detail.setInlayFactoryBatch(inlayDiamond.getFactoryNumber());
	            Double priceType=cdetail.getMidPrice();
	            if(0d==priceType){
	            	detail.setMidPrice(inlayDiamond.getK18Price());
	            }
	            if(1d==priceType){
	            	detail.setMidPrice(inlayDiamond.getPt900Price());
	            }
	            if(2d==priceType){
	            	detail.setMidPrice(inlayDiamond.getPt950Price());
	            }
	            detail.setInlayUserId(inlayDiamond.getUserId());
	    		detail.setState("0");
	    		detail.setOrderDate(DateUtils.getStringDateShort());
	    		detail.setType(inlayDiamond.getInlayType());
	    		detail.setInlayDiamondId(inlayDiamond.getInlayDiamondId());
	    		Clientorder order=clientorderService.findByNO(orderNO);
	    		if(order!=null)detail.setCliOrdMasterId(order.getCliOrdMasterId());
	    		detailService.save(detail);
	    		detailService.updateBySQL(updateOrderTotalPriceSql);
	    		session.remove("batch");
	    		session.remove("orderNo");
	   		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 修改订单，软删除订单
	 * @param parseLong
	 */
	public void delOrder(long orderId) {
		try {
			Clientorder clientorder =(Clientorder) clientorderService.findById(orderId);
			if("0".equals(clientorder.getDelState())){
				clientorder.setDelState("1");
				clientorderService.update(clientorder);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 后台批量软删除订单
	 * @param cliOrderMasterIds
	 * @return
	 */
	public Boolean deleteCliOrder(String[] cliOrderMasterIds) {
		Boolean result = false;
		for(String cliOrderMasterId : cliOrderMasterIds) {
			try {
				Clientorder clientorder =(Clientorder) clientorderService.findById(Long.parseLong(cliOrderMasterId));
				if ("0".equals(clientorder.getDelState())) {
					clientorder.setDelState("1");
					clientorderService.update(clientorder);
					result = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public List findOrderList(Long userId, ClientOrderBO clientOrderBo, ClientorderFacade clientOrderFacade, Integer pageSize)throws Exception {
		return clientorderService.findOrderList(userId, clientOrderBo,clientOrderFacade,pageSize);
	}

	public List findCentOrderList(Long userId, ClientOrderBO clientOrderBo,
			ClientorderFacade clientorderFacade, Integer pageSize) throws Exception {
		return clientorderService.findCentOrderList(userId, clientOrderBo,clientorderFacade,pageSize);
	}
}

